package org.budo.support.javax.servlet.http.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.lang.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class CookieUtil {
    /**
     * 移除指定 cookie
     */
    public static void removeCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 移除所有 cookie
     */
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            removeCookie(response, cookie.getName());
        }
    }

    public static String getCookieValue(Cookie[] cookies, String name) {
        if (null == cookies || null == name) {
            log.debug("#38 cookies={}, name={}", Arrays.toString(cookies), name);
            return null;
        }

        for (Cookie cookie : cookies) {
            if (null != cookie && StringUtil.equals(name, cookie.getName())) {
                return cookie.getValue();
            }
        }

        return null;
    }

    public static String getCookieValue(String cookies, String name) {
        Cookie[] _cookies = stringToCookies(cookies);
        return getCookieValue(_cookies, name);
    }

    public static Cookie[] stringToCookies(String cookies) {
        if (null == cookies || cookies.trim().isEmpty()) {
            log.debug("#53 stringToCookies return null, cookies={}", cookies);
            return null;
        }

        String[] array = cookies.split(";");

        List<Cookie> list = new ArrayList<Cookie>();

        for (String _each : array) {
            if (StringUtil.isNullOrEmpty(_each)) {
                continue;
            }

            String each = StringUtil.trim(_each);
            int i = each.indexOf('=');
            if (i < 0) {
                continue;
            }

            String name = each.substring(0, i);
            String value = each.substring(i + 1);

            list.add(new Cookie(name, value));
        }

        return list.toArray(new Cookie[list.size()]);
    }
}
